# zope imports
from zope.component import adapts
from zope.interface import implements
from zope.interface import Interface

# CMFCore imports
from Products.CMFCore.utils import getToolByName

# CMFPlone imports
from Products.CMFPlone.interfaces import IPloneSiteRoot

# iqpp.plone.simpleimagemapping
from iqpp.plone.simpleimagemapping.interfaces import IMappedImagesManagement
from iqpp.plone.simpleimagemapping.interfaces import IMappedFolder

class MappedImagesManagement:
    """
    """
    adapts(Interface)
    implements(IMappedImagesManagement)
    
    def __init__(self, context):
        """
        """
        self.context = context

    def getMappedImages(self):
        """
        """
        # NOTE: Default content types inherit always, this makes objects which
        # are selected as default documents within folders work.
        mtool = getToolByName(self.context, "portal_membership")        
        images = []
        
        object = self.context
        while IPloneSiteRoot.providedBy(object) == False:

            # try take's care of portal factory
            try:
                for image in object.getBRefs("simpleimagemapping"):
                    if mtool.checkPermission("View", image):
                        images.append(image)

                if len(images) == 0:
                    object = object.aq_inner.aq_parent
                else:                
                    break

            except AttributeError:
                object = object.aq_inner.aq_parent
                        
        images.sort(lambda a, b: cmp(a.getPosition(), b.getPosition()))
        return images


class FolderMappedImagesManagement:
    """
    """
    adapts(IMappedFolder)
    implements(IMappedImagesManagement)
    
    def __init__(self, context):
        """
        """
        self.context = context

    def getMappedImages(self):
        """
        """
        mtool = getToolByName(self.context, "portal_membership")
        images = []
        
        object = self.context
        while IPloneSiteRoot.providedBy(object) == False:
            
            # try takes care of portal factory
            try:
                for image in object.getBRefs("simpleimagemapping"):
                    if mtool.checkPermission("View", image):
                        images.append(image)

                if (len(images) == 0) and (object.getInheritImages() == True):
                    object = object.aq_inner.aq_parent
                else:                
                    break
                    
            except AttributeError:
                object = object.aq_inner.aq_parent
            
        images.sort(lambda a, b: cmp(a.getPosition(), b.getPosition()))
        return images
